//
//  FindPwdStepTableVC1.m
//  Cunli
//
//  Created by lilubin on 15/7/23.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "FindPwdStepTableVC1.h"
#import "NSString+MD5.h"
#import "MyDataService.h"
#import "JKCountDownButton.h"
#import "FindPwdStepTableVC2.h"
#import "SettingTableViewCell.h"
#import "SettingTableViewCell2.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

static NSString *kSettingCellID = @"SettingTableViewCell";

@interface FindPwdStepTableVC1 () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation FindPwdStepTableVC1

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavAttributes];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setNavAttributes
{
    UIImageView *navBgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    [navBgImgView setImage:[UIImage imageNamed:@"NavigationBgImage"]];
    [self.view addSubview:navBgImgView];
    
    UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
    [navLabel setText:@"找回密码"];
    [navLabel setTextColor:[UIColor whiteColor]];
    [navLabel setFont:[UIFont boldSystemFontOfSize:19]];
    navLabel.textAlignment = NSTextAlignmentCenter;
    [navBgImgView addSubview:navLabel];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(8, 27, 30, 30);
    [backBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(kScreenWidth-70, 27, 65, 30);
//    [nextBtn setBackgroundImage:[UIImage imageNamed:@"regnext.png"] forState:UIControlStateNormal];
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:nextBtn];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [self.view addSubview:_tableView];
    
    [_tableView setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
    [self.view setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:kSettingCellID owner:self options:nil].lastObject;
    if (indexPath.row == 0) {
        cell.titleLabel.text = @"+86";
        if (_userName.length != 0) {
            cell.textField.text = _userName;
        }
        cell.textField.placeholder = @"输入手机号";
        cell.textField.font = [UIFont systemFontOfSize:17];
    }
    else
    {
        SettingTableViewCell2 *cell2 = [[NSBundle mainBundle] loadNibNamed:@"SettingTableViewCell2" owner:self options:nil].lastObject;
        cell2.getNumBtnClicked = ^(void){
            [self getCheckNum];
        };
        return cell2;
       
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)nextAction
{
    SettingTableViewCell *cell1 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSString *username = cell1.textField.text;
    
    SettingTableViewCell2 *cell2 = (SettingTableViewCell2 *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    NSString *checkNum = cell2.checkTextField.text;
    
    if (username.length != 11 || checkNum.length != 4) {
        [Config showHUDWithText:@"请检查电话号与验证码" andImage:@"error"];
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:4];
    
    [params setObject:username forKey:@"username"];
    [params setObject:@"fp" forKey:@"ctype"];
    [params setObject:checkNum forKey:@"code"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    [MyDataService requestURL:@"checkcaptcha.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
//        NSLog(@"RegisterVC: Checkcode result:%@", result);
        //将username保存到本地，在后面的界面中还需要用到
        [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"username"] forKey:@"username"];
        
        NSString *response = [result objectForKey:@"response"];
        NSDictionary *captchaDic = [result objectForKey:@"captcha"];
        NSString *code_token = [captchaDic objectForKey:@"code_token"];
        
        if ([response isEqualToString:@"captcha"]) {
            [self pushToSetPasswordVCWithCodeToken:code_token];
        }
        else
        {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *errorStr = [errorDic objectForKey:@"text"];
            [self showHUDWithText:errorStr andImage:@"error"];
            return;
        }
    } failureAction:^{
        [self showHUDWithText:@"验证错误" andImage:@"error"];
        return;
    }];
    
}

- (void)getCheckNum
{
    SettingTableViewCell *cell1 = (SettingTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSString *username = cell1.textField.text;
    
    SettingTableViewCell2 *cell2 = (SettingTableViewCell2 *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    JKCountDownButton *jkBtn = cell2.cellBtn;
    
    if (username.length == 11) {
        jkBtn.enabled = NO;
        //button type要 设置成custom 否则会闪动
        [jkBtn startWithSecond:60];

        [jkBtn didChange:^NSString *(JKCountDownButton *countDownButton,int second) {
            NSString *title = [NSString stringWithFormat:@"%d秒",second];
            return title;
        }];
        [jkBtn didFinished:^NSString *(JKCountDownButton *countDownButton, int second) {
            countDownButton.enabled = YES;
            return @"重新获取";
        }];
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:2]; //获取验证码需要的参数
    
    //设置获取验证码需要的参数：username, rp, sign
    [params setObject:username forKey:@"username"];
    [params setObject:@"fp" forKey:@"ctype"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    //发送获取验证码的请求
    [MyDataService requestURL:@"captcha.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
//        NSLog(@"result:%@", result);
//        NSString *code = [result objectForKey:@"code"];
//        NSString *response = [result objectForKey:@"response"];
//        NSLog(@"response:%@, code:%@", response, code);
        [self showHUDWithText:@"验证码发送成功" andImage:@"done"];
    } failureAction:^{
        [self showHUDWithText:@"验证码获取错误" andImage:@"error"];
    }];
}

- (void)pushToSetPasswordVCWithCodeToken:(NSString *)token
{
    FindPwdStepTableVC2 *findpwdVC = [[FindPwdStepTableVC2 alloc] init];
    findpwdVC.code_token = token;
    findpwdVC.modalPresentationStyle = UIModalPresentationFullScreen;
    findpwdVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:findpwdVC animated:YES completion:NULL];
}

- (void)showHUDWithText:(NSString *)str andImage:(NSString *)imgStr
{
    MBProgressHUD *hud = [Config createHUD];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgStr]];
    hud.labelText = str;
    [hud hide:YES afterDelay:1];
}

@end
